package com.ttxz.sample.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.media.MediaRouter
import android.net.Uri
import android.provider.Settings
import android.view.Display
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.fragment.app.FragmentActivity
import com.ttxz.sample.databinding.ViewDoubleScreenBinding
import com.ttxz.sample.view.widget.MyPresentation

object SecondDisplayUtil {
    private var windowManager: WindowManager? = null
    private var screenBinding: ViewDoubleScreenBinding? = null

    private var myPresentation:MyPresentation?=null
    fun showSecondDisplay(activity: Activity) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            //启动Activity让用户授权
            if (!Settings.canDrawOverlays(activity)) {
                val intent: Intent = Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:${activity.packageName}")
                )
                activity.startActivityForResult(intent, 1010)
                return@showSecondDisplay
            }
        }

        val mediaRouter = activity.getSystemService(Context.MEDIA_ROUTER_SERVICE) as MediaRouter
        val routeInfo: MediaRouter.RouteInfo =
            mediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO)
        val secondDisplay: Display = routeInfo.presentationDisplay
        windowManager = activity.createDisplayContext(secondDisplay).getSystemService(
            FragmentActivity.WINDOW_SERVICE
        ) as WindowManager
        val secondDisplayContext: Context = activity.createDisplayContext(secondDisplay)


        screenBinding = ViewDoubleScreenBinding.inflate(LayoutInflater.from(secondDisplayContext))
        windowManager?.addView(screenBinding?.root, WindowManager.LayoutParams(2003, 3, 3));
    }

    fun hintSecondDisplay() {
        windowManager?.removeView(screenBinding?.root)
    }

    fun showSecondDisplay2(activity: Activity){
        val displayManager: DisplayManager = activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
        var displays = displayManager.displays//获取显示器数组
        myPresentation =MyPresentation(activity, displays[1])
        myPresentation?.window?.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
        myPresentation?.show()
    }

    fun hintSecondDisplay2(){
        myPresentation?.hide()
    }
}